package com.lanyam.travel.base.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanyam.travel.base.entity.ProductTicket;
import com.lanyam.travel.base.entity.ScenicHotel;
import com.lanyam.travel.base.service.IScenicHotelService;
import com.lanyam.travel.base.service.ITicketTypeService;
import com.lanyam.travel.base.utils.Constant;
import com.lanyam.travel.base.utils.FileUtil;
import com.lanyam.travel.base.utils.JSONResult;

/**
 *	 景点/酒店控制器
 * @author asus
 *
 */
@CrossOrigin
@RestController
@RequestMapping("scenic")
public class ScenicHotelController {
	
	@Autowired
	private IScenicHotelService scenicHotelService;
	
	@Autowired
	private ITicketTypeService ticketTypeService;
	
	/**
	 * 增加景点
	 * @param scenicHotel
	 * @return
	 */
	@PostMapping("/addScenic")
	public JSONResult addScenic(@RequestBody ScenicHotel scenicHotel)
	{
		String id = UUID.randomUUID().toString().replace("-", "");
		scenicHotel.setId(id);
		scenicHotel.setCreateTime(new Date());
		scenicHotelService.addScenic(scenicHotel);
		//景区的票类型在这里处理，酒店的房间类型单独在googsInfoController中处理
		List<ProductTicket> ticketTypes = scenicHotel.getTicketTypes();
		if(null != ticketTypes && ticketTypes.size() > 0)
		{
			for (ProductTicket ticket : ticketTypes) {
				ticket.setId(UUID.randomUUID().toString().replace("-", ""));
				ticket.setProductId(id);
				ticketTypeService.createProductTicket(ticket);
			}
		}
		return JSONResult.ok(scenicHotel);
	}
	/**
	 * 追加新增的图片到景点/酒店上，需要先获取原来的图片路径，再把新添加的放在后面，删除走的单独的接口
	 * @param lineId
	 * @param file
	 * @return
	 */
	@RequestMapping("/attachFileToScenic")
	public JSONResult attachFileToScenic(String scenicId,@RequestParam(value = "files", required = false) MultipartFile[] files)
	{
		if(StringUtils.isEmpty(scenicId) || null == files)
		{
			return JSONResult.errorMsg("参数不能为空。");
		}
		ScenicHotel scenic = scenicHotelService.getScenicById(scenicId);
		String dbPathUri = "/img/scenic/"+scenicId;
		String imgUri = FileUtil.uploadFile(files, dbPathUri);
		String oriImg = scenic.getImg();
		if(!StringUtils.isEmpty(oriImg))
		{
			oriImg += ";" + imgUri;
		}
		else
		{
			oriImg = imgUri;
		}
		scenic.setImg(oriImg);
		scenicHotelService.update(scenic);
		return JSONResult.ok(scenic);
	}
	/**
	 * 删除景点/酒店上的图片
	 * @param scenicId
	 * @param fileName 数据库中保存的uri
	 * @return
	 */
	@RequestMapping("/deleteImgInScenic")
	public JSONResult deleteImgInScenic(String scenicId,String fileName)
	{
		if(StringUtils.isEmpty(scenicId) || null == fileName)
		{
			return JSONResult.errorMsg("参数不全");
		}
//		System.out.println("图片路径(格式/scenic/scenicId/name):"+fileName);
		ScenicHotel scenic = scenicHotelService.queryScenicById(scenicId);
//		File tempFile = new File("src/main/resources/static");
		
		String baseUri = Constant.FILE_UPLOAD_BASE_URI;
		File targetFile = new File(baseUri+fileName);
		if(targetFile.exists())
		{
			targetFile.delete();
		}
		String uri = fileName;
		String srcUri = scenic.getImg();
		if(!StringUtils.isEmpty(srcUri))
		{
			String[] srcUris = srcUri.split(";");
			StringBuilder builder = new StringBuilder();
			for (int i = 0; i < srcUris.length; i++) {
				String path = srcUris[i];
				if(!uri.equals(path))
				{
					builder.append(path);
					builder.append(";");
				}
			}
			String img = builder.toString();
			if(img.length() > 0)
			{
				img = img.substring(0,img.length() - 1);
			}
			scenic.setImg(img);
			scenicHotelService.update(scenic);
		}
		
		return JSONResult.ok();
	}
	
	/**
	 * 给景点/酒店增加图片
	 * @param scenicId
	 * @param file
	 * @return
	 */
	@RequestMapping("/addImgToScenic")
	public JSONResult addImgToScenic(String scenicId,@RequestParam(value = "file") MultipartFile file)
	{
		if(StringUtils.isEmpty(scenicId))
		{
			return JSONResult.errorMsg("参数不全");
		}
		ScenicHotel scenic = scenicHotelService.getScenicById(scenicId);
		String img = scenic.getImg();
		int maxNum = 0;
		if(!StringUtils.isEmpty(img))
		{
			String[] imgUris = img.split(";");
			for (int j = 0; j < imgUris.length; j++) {
				String imgUri = imgUris[j];
				int index1 = imgUri.lastIndexOf("/");
				int index2 = imgUri.lastIndexOf(".");
				String name = imgUri.substring(index1, index2);
				try {
					int nameNum = Integer.parseInt(name);
					if(nameNum > maxNum)
					{
						maxNum = nameNum;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		String dbPathUri = "/img/scenic/"+scenicId;
		String fileName = (maxNum+1) + ".png"; 
		String imgUri = FileUtil.uploadFile(file, dbPathUri, fileName);
		scenic.setImg(imgUri);
		scenicHotelService.update(scenic);
		return JSONResult.ok(scenic);
	}
	
	/**
	 * 根据景点/酒店id获取详细信息,包含详细信息
	 * @param id
	 * @return
	 */
	@RequestMapping("getScenicById")
	@ResponseBody
	public JSONResult getScenicById(String id)
	{
		ScenicHotel scenic = scenicHotelService.queryScenicById(id);
		return JSONResult.ok(scenic);
	}
	/**
	 * 删除景点/酒店信息，同步删除详细信息
	 * @param id
	 * @return
	 */
	@RequestMapping("deleteScenicById")
	@ResponseBody
	public JSONResult deleteScenicById(String id)
	{
		if(StringUtils.isEmpty(id))
		{
			return JSONResult.errorMsg("参数不全");
		}
		scenicHotelService.deleteById(id);
		String dbPathUri = "/img/scenic/"+id;
		//如果是更新图片，需要先删除原来存放的图片
		String baseUri = Constant.FILE_UPLOAD_BASE_URI;
		FileUtil.delFolder(baseUri+dbPathUri);
		return JSONResult.ok();
	}
	/**
	 * 更新景点/酒店信息
	 * @param scenicHotel
	 * @return
	 */
	@RequestMapping("updateScenic")
	@ResponseBody
	public JSONResult updateScenic(@RequestBody ScenicHotel scenicHotel)
	{
		scenicHotelService.update(scenicHotel);
		return JSONResult.ok();
	}
	
	/**
	 * 获取后端景点/酒店分页数据
	 * reqMap中的key:name线路名称，region 0为国内1为国外,productType 0为景点1为酒店,
	 * status 0未使用1未使用,location 位置,star 星级,lowPrice 低价,highPrice 高价,startDate 开始日期,endDate 结束日期
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/queryScenicPage")
	public JSONResult queryScenicPage(int page,int pageSize,
				@RequestBody(required = false) Map<String, String> reqMap)
	{
		Page<ScenicHotel> ipage = scenicHotelService.queryScenicPage(page,pageSize,reqMap);
		
		return JSONResult.ok(ipage.getRecords());
	}
	
}
